#include "sdkconfig.h"


#include <stdio.h>
#include <string.h>
#include "esp_vfs_fat.h"
#include "sdmmc_cmd.h"
#include "driver/sdmmc_host.h"
#include "esp_log.h"
#include "sd_card.h"
#include "lvgl.h"

#include "boards/startnorva/config.h"





// #define BSP_SD_CLK          (GPIO_NUM_2)
// #define BSP_SD_CMD          (GPIO_NUM_14)
// #define BSP_SD_D0           (GPIO_NUM_1)

static const char *TAG = "sd_card";

#define MOUNT_POINT              "/sdcard"
#define EXAMPLE_MAX_CHAR_SIZE    64

LV_FONT_DECLARE(font_puhui_20_4);


size_t global_gif_data_size = 0;
uint8_t* global_gif_data = nullptr;


static bool sd_card_mounted = false;

esp_err_t write_text_to_sd(const char* filename, const char* content) {
    if (!sd_card_is_mounted()) {
        ESP_LOGE(TAG, "SD card not mounted");
        return ESP_FAIL;
    }

    char filepath[EXAMPLE_MAX_CHAR_SIZE];
    snprintf(filepath, sizeof(filepath), "%s/%s", MOUNT_POINT, filename);

    FILE* f = fopen(filepath, "w");
    if (f == NULL) {
        ESP_LOGE(TAG, "Failed to open file for writing");
        return ESP_FAIL;
    }

    fprintf(f, "%s", content);
    fclose(f);

    ESP_LOGI(TAG, "File written successfully: %s", filepath);
    return ESP_OK;
}




void sd_card_init()
{

    esp_vfs_fat_sdmmc_mount_config_t mount_config = {
        .format_if_mount_failed = true,
        .max_files = 5,
        .allocation_unit_size = 16 * 1024
    };

    sdmmc_card_t *card;
    const char mount_point[] = MOUNT_POINT;

    ESP_LOGI(TAG, "Initializing SD card");
    ESP_LOGI(TAG, "Using SDMMC peripheral");

    sdmmc_host_t host = SDMMC_HOST_DEFAULT();
    sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
    slot_config.width = 1;
    slot_config.clk = BSP_SD_CLK;
    slot_config.cmd = BSP_SD_CMD;
    slot_config.d0 = BSP_SD_D0;
    // 修改为禁用内部上拉，使用外部上拉电阻
    slot_config.flags &= ~SDMMC_SLOT_FLAG_INTERNAL_PULLUP;

    ESP_LOGI(TAG, "Mounting filesystem");
    esp_err_t ret = esp_vfs_fat_sdmmc_mount(mount_point, &host, &slot_config, &mount_config, &card);

    if (ret != ESP_OK) {
        if (ret == ESP_FAIL) {
            ESP_LOGE(TAG, "Failed to mount filesystem. ");
        } else {
            ESP_LOGE(TAG, "Failed to initialize the card (%s). ", esp_err_to_name(ret));
        }

        // 清空屏幕
        lv_obj_clean(lv_scr_act());

        // 创建一个标签显示错误信息
        lv_obj_t * label = lv_label_create(lv_scr_act());
        lv_label_set_text(label, "内存卡加载失败");

        // 居中显示标签
        lv_obj_center(label);
        lv_obj_set_style_text_font(label, &font_puhui_20_4, 0);

        // 阻塞所有任务，进入无限循环
        while (1) {
            vTaskDelay(portMAX_DELAY);
        }
    }

    ESP_LOGI(TAG, "Filesystem mounted");
    sdmmc_card_print_info(stdout, card);
    sd_card_mounted = true;
    // 在需要写入文件的地方调用
    write_text_to_sd("test.txt", "Hello, this is a test file from ESP32!");
}



// 添加SD卡挂载状态检查函数
bool sd_card_is_mounted(void) {
    return sd_card_mounted;
}